package com.googlecode.restitory.api.gae;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

public class JsonCallbackHandler {

	private static final JsonCallbackHandler ME = new JsonCallbackHandler();

	private List<JsonCallback> callbacks = new ArrayList<JsonCallback>();

	private JsonCallbackHandler() {

	}

	public static JsonCallbackHandler instance() {
		return ME;
	}

	public void add(JsonCallback... callback) {
		callbacks.addAll(Arrays.asList(callback));
	}

	public void add(Collection<? extends JsonCallback> callbacks) {
		this.callbacks.addAll(callbacks);
	}

	public List<JsonCallback> get(String path) {
		List<JsonCallback> ret = new ArrayList<JsonCallback>();
		for (JsonCallback callback : callbacks) {
			List<String> prefs = callback.getPaths();
			if (prefs == null) {
				ret.add(callback);
				continue;
			}

			for (String pref : prefs) {
				if (path.startsWith(pref)) {
					ret.add(callback);
					continue;
				}
			}
		}
		return ret;
	}

}
